package com.zbw.printlibrary.activity;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.zbw.printlibrary.R;
import com.zbw.printlibrary.printConnector.IPrintCallBack;
import com.zbw.printlibrary.printConnector.IPrinterControl;
import com.zbw.printlibrary.printConnector.NewPrint;
import com.zbw.printlibrary.util.UsbController;
import java.util.HashMap;
import static com.zbw.printlibrary.printConnector.NewPrint.PRINT_USB;

public class PrintUsbActivity extends AppCompatActivity implements View.OnClickListener,IPrintCallBack {
    private RelativeLayout rela_back;
    private Button but_next, but_print,but_open_box;
    private TextView tv_show;
    private UsbManager mUsbManager;
    private PendingIntent permissionIntent;
    private static final String ACTION_USB_PERMISSION = "com.example.android_print.USB_PERMISSION";
    public UsbController usbCtrl;
    public UsbDevice dev;
    private int step_index = 0;
    private int USB_VID;
    private int USB_PID;
    HashMap<String, UsbDevice> deviceList1, deviceList2;
    private int size1, size2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏系统通知栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
        setContentView(R.layout.activity_print_usb);
        setActivitySize();
        initUI();
        initializer();
    }

    private void initUI() {
        rela_back = (RelativeLayout) findViewById(R.id.rela_back);
        rela_back.setOnClickListener(this);
        but_next = (Button) findViewById(R.id.but_next);
        but_next.setOnClickListener(this);
        but_print = (Button) findViewById(R.id.but_print);
        but_print.setOnClickListener(this);
        but_open_box = (Button) findViewById(R.id.but_open_box);
        but_open_box.setOnClickListener(this);
        tv_show = (TextView) findViewById(R.id.tv_show);
    }

    /**
     * 动态设置Activity的大小。
     */
    private void setActivitySize() {
        //动态设置Activity的大小。
        Display display = getWindowManager().getDefaultDisplay(); // 为获取屏幕宽、高
        Window window = getWindow();
        WindowManager.LayoutParams windowLayoutParams = window.getAttributes(); // 获取对话框当前的参数值
        windowLayoutParams.width = (int) (display.getWidth() * 0.3); // 宽度设置为屏幕的0.7
        windowLayoutParams.height = (int) (display.getHeight() * 0.4); // 高度设置为屏幕的0.7
        windowLayoutParams.alpha = 1f;// 设置透明度
        getWindow().setAttributes(windowLayoutParams);
    }

    private void initializer() {
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        usbCtrl = new UsbController(this, mHandler);
    }


    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                default:
                    break;
            }
        }
    };

    @Override
    public void onClick(View view) {
        if (view.getId()==R.id.rela_back) {
            finish();
        }else if(view.getId()==R.id.but_next){
            step_index++;
            stepProcess();
        }else if(view.getId()==R.id.but_print){
            try {
                printStart();
            } catch (Exception e) {
                Toast.makeText(this,"请先连接USB打印机",Toast.LENGTH_SHORT).show();
            }
        } else if (view.getId()==R.id.but_open_box) {
            try {
                usbCtrl.openCashBox(dev);
            } catch (Exception e) {
                Toast.makeText(this,"请先连接USB开钱箱",Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void printStart() {
        String msg = "";
        byte[] cmd = new byte[3];
        cmd[0] = 0x1b;
        cmd[1] = 0x21;
        cmd[2] |= 0x10;
        usbCtrl.sendByte(cmd, dev); // 倍宽、倍高模式
        usbCtrl.sendMsg("　　　　　　　智百威\n", "GBK", dev);
        cmd[2] &= 0xEF;
        usbCtrl.sendByte(cmd, dev); // 取消倍高、倍宽模式
        msg = "  您已经成功的连接上了usb打印机！\n\n" + " 你好 \n\n" + "   打印成功！  \n\n";
        usbCtrl.sendMsg(msg, "GBK", dev);
    }

    @SuppressLint("NewApi")
    private void stepProcess() {
        System.out.println("step = " + step_index);
        if (step_index == 1) {
            deviceList1 = mUsbManager.getDeviceList();
            size1 = deviceList1.size();
            System.out.println("size 1 = " + size1);
            tv_show.setText("请接上打印机，然后点下一步");
        } else if (step_index == 2) {
            but_next.setVisibility(View.GONE);
            but_print.setVisibility(View.VISIBLE);
            but_open_box.setVisibility(View.VISIBLE);
            deviceList2 = mUsbManager.getDeviceList();
            size2 = deviceList2.size();
            System.out.println("size 2 = " + size2);
            int ret = 0;
            for (UsbDevice device2 : deviceList2.values()) {
                boolean flag = true;
                for (UsbDevice device1 : deviceList1.values()) {
                    System.out.println("vid 1 = " + device1.getVendorId()
                            + " pid 1 = " + device1.getProductId());
                    System.out.println("vid 2 = " + device2.getVendorId()
                            + " pid 2= " + device2.getProductId());
                    if (device2.getVendorId() == device1.getVendorId()
                            && device2.getProductId() == device1.getProductId()) {
                        System.out.println("same usb device");
                        flag = false;
                        break;
                    } else {
                        continue;
                    }
                }
                System.out.println("flag = " + flag);
                if (flag) {
                    System.out.println("vid = " + device2.getVendorId()
                            + " pid = " + device2.getProductId());
                    System.out.println("find new usb device");
                    initPrint(device2.getVendorId(), device2.getProductId());
                    ret = 1;

                }
            }
            if (ret == 0) {
                tv_show.setText("没有找到打印机，请返回，然后再按照提示步骤来一次");
            }
        }
    }

   /* <string name="no_print">没有找到打印机，请返回，然后再按照提示步骤来一次</string>
    <string name="connect_print">已连接上打印机，可以打印测试页</string>
    <string name="unplug_print">请先拔出打印机，然后点下一步</string>*/

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (usbCtrl != null) {
            usbCtrl.close();
            usbCtrl = null;
        }
    }

    private void initPrint(int vid, int pid) {
        dev = usbCtrl.getDev(vid, pid);
        if (dev != null) {
            if (!(usbCtrl.isHasPermission(dev))) {
                // Log.d("usb调试","请求USB设备权限.");
                usbCtrl.getPermission(dev);
            }
            tv_show.setText("已连接上打印机，可以打印测试页");

            USB_VID = vid;
            USB_PID = pid;
            SaveData();
        }
    }


    private void myTest() {
        HashMap<String, UsbDevice> myDeviceList = mUsbManager.getDeviceList();
        for (int i = 0; i < myDeviceList.size(); i++) {
            myInitPrint(myDeviceList.get(i).getVendorId(),myDeviceList.get(i).getProductId());
        }
    }

    private void myInitPrint(int vid, int pid) {
        dev = usbCtrl.getDev(vid, pid);
        if (dev != null) {
            if (!(usbCtrl.isHasPermission(dev))) {
                // Log.d("usb调试","请求USB设备权限.");
                usbCtrl.getPermission(dev);
            }
            tv_show.setText("已连接上打印机，可以打印测试页");

            USB_VID = vid;
            USB_PID = pid;
            SaveData();
        }
    }

    //保存数据
    public void SaveData() {
        //指定操作的文件名称
        SharedPreferences share = getSharedPreferences("SHEZHI", MODE_PRIVATE);
        SharedPreferences.Editor edit = share.edit(); //编辑文件
        edit.putInt("USB_VID", USB_VID);
        edit.putInt("USB_PID", USB_PID);
        edit.commit();  //保存数据信息
    }


    @Override
    public void onConnect(String message, boolean b) {

    }

    @Override
    public void onDisConnect(String message, boolean b) {

    }

    @Override
    public void onPrintResult(boolean resultCode) {

    }
}
